<?php 
namespace app\index\controller;

use app\common\model\Carousel as CarouselModel;
use app\common\model\Article;
use app\common\model\Badge;
use app\common\controller\Richtext;
use think\Request;
use think\Exception;
use app\common\model\Message;
use app\common\model\ArticleEval;

class Index extends Base
{
	
	private $article;
	
	public function initialize()
	{
		$this->article = new Articles();
	}
	/**
	 * 博客首页
	 * @return unknown
	 */
	public function index()
	{
		//获取轮播图
		$carousel = CarouselModel::where(['state' => 1])->select();
		//获取文章列表
		//$article = $this->article->getArticle();
		$article = $this->getAricles();
		//获取标签库
		$badges = $this->article->getBadges();
		//获取点击排行文章
		$sort =   $this->article->getSort();
		//获取博主信息
		$bloger = $this->article->getBloger();
		//获取系统推荐文章
		$comments = $this->article->getComments();
		//随机获取评论
		$evals = db()->query($sql = "SELECT * FROM `db_article_eval` ORDER BY RAND() LIMIT 30");
		$list = [
				'article' => $article,  //文章列表
				'badges' => $badges, //标签库
				'comment' => $comments , //推荐列表
				'sort' => $sort ,//排行
				'bloger' => $bloger, //博主信息,
				'evals' => $evals
		];
		$this->assign('list',json_encode($list));
		return view();
	}
	
	/**
	 * 用户留言
	 * @param Request $request
	 * @throws Exception
	 */
	public function message(Request $request)
	{
		$data = $request->param('');
		try {
			if(!$data['user_name'])throw new Exception('请输入名称');
			if(!$data['email'])throw new Exception('请输入邮箱');
			if(!$data['content'])throw new Exception('请输入内容');
			$data['create_time'] = time();
			Message::create($data);
		} catch (Exception $e) {
			return $this->error($e->getMessage());
		}
		return $this->success('留言成功');
	}
	
	public function getArticle(Request $request)
	{
		$data = $request->param('');
		$where = [['state','>',0]];
		if(array_key_exists('badge', $data)){
			$where[] = ['badge','=',$data['badge']];
		}
		$list = Article::where($where)->order('state desc,id desc')->paginate(10)->toArray();
		foreach ($list['data'] as &$rows) {
			$rows['content'] = Richtext::getStirng($rows['content'],100).'...';
			$rows['badge_name'] = Badge::get($rows['badge'])->name;
		}
		if ($request -> isAjax()) {
			return $this->success($list);
		} 
		
	}
	
	private function getAricles()
	{
		$list = Article::where([['state','>',0]])->order('state desc,id desc')->paginate(10)->toArray();
		foreach ($list['data'] as &$rows) {
			$rows['content'] = Richtext::getStirng($rows['content'],100).'...';
			$rows['badge_name'] = Badge::get($rows['badge'])->name;
		}
		return $list;
	}
	
}